package com.atjava.nebula.weixin.ssl;


import java.io.File;
import java.io.IOException;

import com.atjava.nebula.web.ssl.HttpsClient;

import net.sf.json.JSONObject;

public class WeixinGetMediaID {
	
	private static final String UPLOAD_URL = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=";
	private static final String IMAGE_TYPE = "&type=image";
	private static final String VIDEO_TYPE = "&type=video";
	private static final String VOICE_TYPE = "&type=voice";
	private static final String FILE_TYPE = "&type=file";
	private static final String MPNEWS_TYPE = "&type=mpnews";
	
	public static String getFileMediaID(String filePath,String access_token) throws IOException {

		File file = new File(filePath);
		
		if (!file.exists() || !file.isFile()) {
		throw new IOException("文件不存在");
		}
		String extend = file.getName().substring(file.getName().lastIndexOf("."), file.getName().length());
		String type = null;
		
		if(".MP4".equalsIgnoreCase(extend)){
			type = VIDEO_TYPE;
		}else if(".JPG".equalsIgnoreCase(extend) || ".PNG".equalsIgnoreCase(extend)){
			type = IMAGE_TYPE;
		}else if (".WAV".equalsIgnoreCase(extend) || ".MP3".equalsIgnoreCase(extend)){
			type = VOICE_TYPE;
		}else{
			type = FILE_TYPE;
		}
		
		HttpsClient client = new HttpsClient();
		String response = client.getFileMediaIdByPostMothod(UPLOAD_URL+access_token+type, file);
		System.out.println(response);
		JSONObject jsonObj = JSONObject.fromObject(response);
		String mediaId = null;
		if(jsonObj.containsKey("media_id")){
			mediaId = jsonObj.getString("media_id");
		}
		
		return mediaId;
}
	
}
